package com.xnj.testweb.common.Interceptor;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.xnj.testweb.admin.mapper.SysUserMapper;
import com.xnj.testweb.common.annotation.LimitAnnotation;
import com.xnj.testweb.common.constants.Constants;
import com.xnj.testweb.common.exeception.CommonException;
import com.xnj.testweb.core.UserRoleVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class MyLogAspect {

//    @Autowired
//    private ManagementLogService managementLogService;

//    @Autowired
//    private SysUserService userService;

//    @Autowired
//    private RedisUtils redisUtils;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Pointcut("@annotation(com.xnj.testweb.common.annotation.LimitAnnotation)")
    public void myLogPointcut() {
    }

    @Before("myLogPointcut()")
    public void logHttpInfo(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LimitAnnotation annotation = method.getAnnotation(LimitAnnotation.class);
        String limit = annotation.userLimit();


        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = String.valueOf(tokenInfo.getLoginId());
        if (loginId != null && !loginId.isEmpty()) {
            int id = Integer.parseInt(loginId);

            UserRoleVo roleVo = sysUserMapper.selectTestRole(id);
            // 如果是 admin 跳过验证
            if (roleVo.getRoleType().equals("admin")) {
                // 结束，跳过
                return;
            }

//            List<String> list = new ArrayList<>();
//            list.add("user.add");
//            list.add("user.delete");
//            list.add("user.get");
//            list.add("user.update");


            // 查询角色权限
            List<String> roleList = sysUserMapper.RoleList(roleVo.getId());
            boolean contains = roleList.contains(limit);
            if (!contains) {
                // 没有权限
                throw new CommonException(Constants.NOLIMIT, "该角色没有权限");
            }

            // 相应角色 只能看到 不用的菜单
        }
    }
}
